package com.itheima.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.R;
import com.itheima.properotes.Ossproperites;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Slf4j
@RequestMapping("/common")
@RestController
public class CommonController {
    @Autowired
    private Ossproperites ossproperites;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();

        log.info("getEndpoint:{},getAccessKey:{},{}",ossproperites.getEndpoint(), ossproperites.getAccessKey(), ossproperites.getSecret());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossproperites.getEndpoint(), ossproperites.getAccessKey(), ossproperites.getSecret());

       // 文件重命名
//        String originalFilename = file.getOriginalFilename();
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String fileName1 =
//        String fileUrl = fileName1 + suffix;
        try {
            ossClient.putObject(ossproperites.getBucketName(), fileName, new ByteArrayInputStream(file.getBytes()));

        } catch (Exception ce) {
            throw new IOException("文件上传异常");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            //需要用url作为返回值 返回才可以把图片读到公共的展示上.
            String url ="http://"+ossproperites.getBucketName()+"."+ossproperites.getEndpoint()+"/"+fileName;
            log.info(url);
            return R.success (url);
        }
    }
}
